﻿// ===============================================================================
// XCI.NET 西安交通信息WinForm开发框架 2018 版权所有
// ===============================================================================
using System.Collections.Concurrent;
using System.Collections.Generic;

namespace XCI.Helper
{
    /// <summary>
    /// 静态数据操作类
    /// </summary>
    public static class StaticHelper
    {
        private static readonly ConcurrentDictionary<string, object> CacheObj = new ConcurrentDictionary<string, object>();

        /// <summary>
        /// 获取对象
        /// </summary>
        /// <param name="key">键名</param>
        /// <returns>返回对象,如果不存在指定的键名返回null</returns>
        public static object Get(string key)
        {
            CacheObj.TryGetValue(key, out object find);
            return find;
        }

        /// <summary>
        /// 获取对象,如果不存在指定的键名则把对象加到静态数据中
        /// </summary>
        /// <param name="key">键名</param>
        /// <param name="obj">对象</param>
        /// <returns>返回对象,如果不存在指定的键名返回指定的对象</returns>
        public static object GetOrAdd(string key, object obj)
        {
            return CacheObj.GetOrAdd(key, obj);
        }

        /// <summary>
        /// 判断是否存在对象Key
        /// </summary>
        /// <param name="key">键名</param>
        public static bool Contain(string key)
        {
            return CacheObj.ContainsKey(key);
        }

        /// <summary>
        /// 把对象写入静态数据中
        /// </summary>
        /// <param name="key">键名</param>
        /// <param name="obj">对象</param>
        public static void AddOrUpdate(string key, object obj)
        {
            CacheObj.AddOrUpdate(key, obj, (k, o) => obj);
        }

        /// <summary>
        /// 把对象从缓存中移除
        /// </summary>
        /// <param name="key">键名</param>
        /// <returns>成功返回true</returns>
        public static bool Remove(string key)
        {
            return CacheObj.TryRemove(key, out object obj);
        }

        /// <summary>
        /// 清空缓存
        /// </summary>
        public static void Clear()
        {
            CacheObj.Clear();
        }
    }
}
